package com.simoniu.first.servlet;

import com.simoniu.first.service.UsersService;
import com.simoniu.first.service.impl.UsersServiceImpl;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet(name = "UsersServlet", value = "/users")
public class UsersServlet extends HttpServlet {
    private String action = "queryById";

    private UsersService usersService = new UsersServiceImpl();

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        if (request.getParameter("action") != null) {
            this.action = request.getParameter("action");
        }

        switch (this.action) {
            case "login":
                login(request, response);
                break;
        }
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request, response);
    }

    //用户登录业务逻辑
    private void login(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String username = request.getParameter("username");
        String password = request.getParameter("password");

        if (usersService.login(username, password)) {
            response.sendRedirect(request.getContextPath() + "/login_success.html");
        } else {
            response.sendRedirect(request.getContextPath() + "/login_failure.html");
        }
    }

}
